package com.jj.filter;


import com.alibaba.fastjson.JSONObject;
import com.jj.pojo.Result;
import com.jj.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        强制转换为HttpServletRequest和HttpServletResponse
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
//        1.获取请求url
            String url = req.getRequestURL().toString();
            log.info("请求的url:{}", url);
//        2.判断请求url是否包含login，如果包含，放行
            if (url.contains("login")){
                log.info("登录请求...");
                chain.doFilter(request, response);
                return;
            }
//        3.获取请求头中的令牌token
            String jwt = req.getHeader("token");
//        4.判断令牌是否为空，如果为空，拦截，返回错误信息
//        StringUtils.hasLength用于判断字符串长度，如果为空，返回false，不为空，返回true
        if (!StringUtils.hasLength(jwt)){
            log.info("令牌为空，拦截");
            Result error = Result.error("未登录");
//            手动转换对象-json,添加依赖fasterjson
            String notLogin = JSONObject.toJSONString(error);
//            将JSON格式的错误信息写入响应体
            resp.getWriter().write(notLogin);
            return;
        }
//        5.解析token，如果解析失败，拦截，返回错误信息
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，拦截");
            Result error = Result.error("未登录");
//            手动转换对象-json,添加依赖fasterjson
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }
//        6.放行
            log.info("放行");
            chain.doFilter(request, response);
    }
}
